import { Sequelize } from 'sequelize'
import path from 'path'
import fs from 'fs'
import { initModels } from './models/init-model'
import { app } from 'electron'

let sequelize: Sequelize

async function initDatabase() {
  let dbFilePath = ''
  if (sequelize === undefined) {
    if(app.isPackaged){
      let app_path = app.getAppPath()
      app_path = app_path.replaceAll('\\app.asar', '') //  asar开启
      dbFilePath = path.join(app_path, '/db/mydb.db')
    }else {
      dbFilePath = path.join(path.join(__dirname, '..'), '../db/mydb.db')
    }
    // dbFilePath = path.resolve('resource/db/mydb.db')
    console.log(dbFilePath)
    if (!fs.existsSync(dbFilePath)) {
      console.log('mydb.db 文件路径不存在!')
    }
    sequelize = new Sequelize({
      dialect: 'sqlite',
      storage: dbFilePath,
      logging: true,
      logQueryParameters: true
    })
    await sequelize.authenticate().then(() => {
        console.log('authenticate')
        initModels(sequelize)
      }).catch((e) => {
        console.log(e)
      }).finally(() => {})
  }
  //同步模型,否则可能调用模型时找不到表
  await sequelize.sync()
}

export default initDatabase
